package com.zr.planClass.service.impl;

import com.zr.planClass.mapper.PlanClassMapper;
import com.zr.planClass.model.*;
import com.zr.planClass.service.PlanClassService;
import com.zr.util.*;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.*;

/**
 * Created by Administrator on 2019/12/20.
 */
@Service
@Transactional
public class PlanClassSerImpl implements PlanClassService{

    @Autowired
    private PlanClassMapper planClassMapper;

    @Override
    public ResultVo add(@Valid PlanClassVo planClassVo) {

        /*参数中添加session,可以得到登录人的姓名,可以给修改人进行赋值 ses.getAtt.....*/
        ResultVo yanzheng = yanzheng(planClassVo);

        if (!yanzheng.getSuccess()){
            return yanzheng;
        }

        PlanClassAllVo planClassAllVo = new PlanClassAllVo();
        BeanUtils.copyProperties(planClassVo,planClassAllVo);

        /*Date nowDate = new Date();*/
        planClassAllVo.setCreateName("张三");
        planClassAllVo.setCreateTime(planClassVo.getCreateTime());
        planClassAllVo.setUpdateName("张三");
        planClassAllVo.setUpdateTime(planClassVo.getUpdateTime());

        planClassMapper.addPlanClass(planClassAllVo);
        return ResultVoBuilder.success();
    }

    @Override
    public PlanClassAllVo queryById(Integer id) {
        PlanClassAllVo planClassAllVo = planClassMapper.queryById(id);
        return planClassAllVo;
    }

    @Override
    public ResultVo update(@Valid PlanClassVo planClassVo) {

        /*ResultVo yanzheng = yanzheng(planClassVo);*/
        PlanClassAllVo planClassAllVo2 = planClassMapper.queryById(planClassVo.getId());
        int nameCount =  planClassMapper.queryByName(planClassVo.getName());
        if (nameCount>0){

            if (planClassVo.getName().equals(planClassAllVo2.getName())){
                planClassMapper.updatePlanClass(planClassVo);
                return ResultVoBuilder.success();
            }
            return ResultVoBuilder.error(ErrorMessageClass.PLANCLASSADD);
        }


        PlanClassAllVo planClassAllVo = new PlanClassAllVo();
        BeanUtils.copyProperties(planClassVo,planClassAllVo);
        Date nowDate = new Date();
        planClassVo.setUpdateName("李四");
        planClassVo.setUpdateTime(nowDate);


        planClassMapper.updatePlanClass(planClassVo);
        return ResultVoBuilder.success();

    }



    @Override
    @Transactional
    public ResultVo updateStudas(@Valid PlanStutas planStutas) {

        /*修改的数据是否存在*/
        PlanClassAllVo planClassAllVo = planClassMapper.queryById(planStutas.getId());
        if (planClassAllVo == null){
            return ResultVoBuilder.error("修改对象不存在");
        }

        /*数据转换*/
        /*修改数据库*/
        PlanClassVo planClassVo = new PlanClassVo();
        BeanUtils.copyProperties(planStutas,planClassVo);

        Date nowDate = new Date();

        planClassVo.setUpdateName("张三");
        planClassVo.setUpdateTime(nowDate);

        planClassMapper.updateStudas(planStutas);
        return ResultVoBuilder.success();
    }

    @Override
    public ResultVo getPage(PageSelectVo pageSelectVo) {

        /*查询当前页信息*/
        List<PlanClassAllVo> list = planClassMapper.getPage(pageSelectVo);
        if (!CollectionUtils.isEmpty(list)){
            for (PlanClassAllVo planClassAllVo :list) {
                if (planClassAllVo.getStatus()!=null){
                    if (!planClassAllVo.getStatus()){
                        planClassAllVo.setStatusName("禁用");
                    }
                    if (planClassAllVo.getStatus()){
                        planClassAllVo.setStatusName("启用");
                    }
                }

            }
        }


        /*查询条数*/
        Integer countTotal = planClassMapper.getCount(pageSelectVo);
        AllRecords allRecords = new AllRecords();
        allRecords.setDataList(list);
        allRecords.setTotalNumber(countTotal);
        allRecords.setPageIndex(pageSelectVo.getPageIndex());
        allRecords.setPageSize(pageSelectVo.getPageSize());
        allRecords.resetTotalNumber(countTotal);
        return ResultVoBuilder.success(allRecords);
    }

    @Override
    public ResultVo importPlanClass(MultipartFile file) throws Exception{
//        1.给用户提供导入模板
//        2.提示版本问题，询问产品经理支持哪种版本的导入格式，使用2007版本的导入模板，根据版本不同，poi导入技术的读取方式不同

        if (!file.getOriginalFilename().contains("xlsx")){
            return ResultVoBuilder.error("文档版本不同,请改为xlsx版本再试");
        }

//        3.模板是否是需要导入的模板，验证模板是否正确
        //通过获得文档里面的内容,进行判断,该文档是否正确
        XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
        //获取单元格中的信息 at0是获取sheet1中的数据。
        XSSFSheet sheet = workbook.getSheetAt(0);
        System.out.println(sheet.getRow(sheet.getFirstRowNum()).getCell(0));
        //验证第一列第一行的表格标头信息是否为 “询价单导入”，如果不是，提示模板错误。
        if (!String.valueOf(sheet.getRow(sheet.getFirstRowNum()).getCell(0)).equals("计划大类导入模板")) {
            return ResultVoBuilder.error("模板错误,请重新创建");
        }

        List<PlanClassAdd> planList = new ArrayList<>();
        //遍历excel表格中的所有数据，从第五行开始读取，没有数据时终止遍历。
        for (int i = sheet.getFirstRowNum() + 4; i <= sheet.getLastRowNum(); i++) {
            //读取每一行的数据
            XSSFRow xssfRow = sheet.getRow(i);
            if(xssfRow!=null) {

                String test1 = String.valueOf(xssfRow.getCell(1)).trim();
                String test2 = String.valueOf(xssfRow.getCell(2)).trim();
                String test3 = String.valueOf(xssfRow.getCell(3)).trim();
                if (!test1.equals("")&&!test1.equals("null")
                        ||!test2.equals("")&&!test2.equals("null")
                        ||!test3.equals("")&&!test3.equals("null")){
                    //把每一行的数据放入到实体类中
                    ResultVo<PlanClassAdd> inquiryImportVo = build(xssfRow);
                    if (!inquiryImportVo.getSuccess()){
                        return inquiryImportVo;
                    }
                    //把实体类中的数据放入到list集合中
                    planList.add(inquiryImportVo.getData());
                }

            }
        }

        //6.验证字符长度是否符合需求
        //5.验证不为空字段是否为空
        ResultVo resultVo1 = checkNotNull(planList);
        if (!resultVo1.getSuccess()){
            return resultVo1;
        }

        System.out.println("------------"+planList);
        //8.验证数据是否重复
        ResultVo resultVo = checkRepeat(planList);
        if (!resultVo.getSuccess()){
            return resultVo;
        }
        //7.验证数据是否存在也就是是否合法
        ResultVo resultVo2 = checkCunZai(planList);
        if (!resultVo2.getSuccess()){
            return resultVo2;
        }

        /*planList.removeAll(queryList);*/

        System.out.println("+++++++++++++++"+planList);
        /*添加数据*/
        planClassMapper.insertList(planList);

        return ResultVoBuilder.success();

    }

    private ResultVo checkCunZai(List<PlanClassAdd> planList) {

        //7.验证数据是否存在也就是是否合法
        List<PlanClassAdd> queryList = planClassMapper.queryByList(planList);

        System.out.println("%%%%%%%%%%%%%%%%"+queryList);
        if (queryList.size()>0) {

           /* planList.removeAll(queryList);
            *//*添加数据*//*
            planClassMapper.insertList(planList);*/

            return ResultVoBuilder.error("有存在的备件大类,重复的为:" + queryList);
        }
        return ResultVoBuilder.success();
    }

    private ResultVo checkNotNull(List<PlanClassAdd> planList) {
      /* //遍历excel表格中的所有数据，从第五行开始读取，没有数据时终止遍历。
        for (int i = sheet.getFirstRowNum() + 4; i <= sheet.getLastRowNum(); i++) {
            //读取每一行的数据
            XSSFRow xssfRow = sheet.getRow(i);
            if (String.valueOf(xssfRow.getCell(i)).length()>100){
                return ResultVoBuilder.error("存在数据过长,请校验后,重试");
            }
        }*/
        //6.验证字符长度是否符合需求
        //5.验证不为空字段是否为空
        System.out.println("============"+planList);
        for (PlanClassAdd plan:planList) {

            if (plan.getCode()=="" || plan.getCode()==null){
                return ResultVoBuilder.error("编号不能为空");
            }else{
                if (plan.getCode().length()>30){
                    return ResultVoBuilder.error("编码的长度不能超过30字节");
                }
            }
            if (plan.getName()=="" || plan.getName()==null){
                return ResultVoBuilder.error("名称不能为空");
            }else{
                if (plan.getName().length()>30){
                    return ResultVoBuilder.error("名称的长度不能超过30字节");
                }
            }

            if(StatusEnum.getValue(plan.getStatusName())==null){

                System.out.println(plan.getStatusName()+"^^^^^^^^^^^^^^^");
                System.out.println(StatusEnum.getValue(plan.getStatusName())+"[][]][[[[[[[[[[[[[[[[[[[[");
                return ResultVoBuilder.error("状态名称只能为启用或者禁用");
            }else{
                //9.对于需要转换的数据进行数据转换，比如数据库存的数据为数字格式，用户输入的为汉字，需要把汉字转换为数字存储
                System.out.println(plan.getStatusName()+"**********");
                System.out.println(StatusEnum.getValue(plan.getStatusName())+"/////////////");
                Integer status = StatusEnum.getValue(plan.getStatusName());
                Boolean booleanStatus = (status==1)?true:false;
                plan.setStatus(booleanStatus);
            }
        }

        return ResultVoBuilder.success();
    }

    private ResultVo checkRepeat(List<PlanClassAdd> planList) {
        List<String> codeList = new ArrayList<>();
        for (PlanClassAdd plan:planList) {
            codeList.add(plan.getCode());
        }

        /*Set<String> codeSet = new HashSet<>(codeList);
        if (codeSet.size()!=codeList.size() ){
            return ResultVoBuilder.error("有重复计划大件");
        }*/
        List<String> newcodeList = new ArrayList<>();
        List<String> repeatcodeList = new ArrayList<>();
        for (String code:codeList) {

            if (newcodeList.contains(code)){
                repeatcodeList.add(code);
            }
            newcodeList.add(code);
        }
        if (repeatcodeList.size()>0){
            return ResultVoBuilder.error("有重复的计划大类,重复的为:"+repeatcodeList);
        }
        return ResultVoBuilder.success();
    }

    public ResultVo build(XSSFRow xssfRow){
        PlanClassAdd planClassAdd = new PlanClassAdd();
        //     4.格式问题，必须保持统一格式，统一为字符串格式导入
        try {
            planClassAdd.setCode(String.valueOf(xssfRow.getCell(1)));
        }catch (Exception e){
            return ResultVoBuilder.error("请检查编码格式是否为字符串格式");
        }

        planClassAdd.setName(String.valueOf(xssfRow.getCell(2)));
        planClassAdd.setStatusName(String.valueOf(xssfRow.getCell(3)));
        planClassAdd.setRemark(String.valueOf(xssfRow.getCell(4)));
        return ResultVoBuilder.success(planClassAdd);
    }

    public ResultVo yanzheng(PlanClassVo planClassVo){
        //根据名称传递数据,查看是否存在数据
        int nameCount =  planClassMapper.queryByName(planClassVo.getName());
        if (nameCount>0) {

            return ResultVoBuilder.error(ErrorMessageClass.PLANCLASSADD);
        }
        return ResultVoBuilder.success();
    }
}
